var nid, cxturi, cxtrowkey, graph, nodeW = 30,
    nodeH = 30,
    posx = 0,
    posy = 0,
    saveauto = false;
var pid = window.location.href.split("?")[1].slice(4, window.location.href.split("?")[1].lastIndexOf("&"));
var owneridcard = JSON.parse(localStorage.getItem('loginMsg')).data.adminUser.sfzh;

console.log(JSON.parse(localStorage.getItem("loginMsg")))
let loginMsg = JSON.parse(localStorage.getItem("loginMsg")).data
let wsuri = "ws://120.131.13.133:10011/caseGraph/" + loginMsg.adminUser.xm + "/" + loginMsg.adminUser.sfzh + "/" + pid
let websock = new WebSocket(wsuri)
websock.onopen = function(e) {
    console.log(e)
}
websock.onmessage = function(e) {
    if (document.hidden) {
        noticeMsg("司南系统有新的研判结果！")
    }
    getGraph()
}
layui.use('table', function() {
    var table = layui.table;

    table.render({
        elem: '#test',
        url: 'json/sx-list.json',
        cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,
        cols: [
            [
                { field: 'id', width: 280, title: '关联类型名称', sort: true }, { field: 'username', title: 'URL' }, { field: 'sex', width: 280, title: '已弃用', sort: true }
            ]
        ]
    });
});


//初始化关联图
var cy = cytoscape({
    container: $('#relationBox'),
    //boxSelectionEnabled: true,
    //zoomingEnabled:true,
    //panningEnabled:true,
    //userPanningEnabled:true,
    //autounselectify: true,
    //styleEnabled: true,
    minZoom: 0.5,
    maxZoom: 2,
    Zoom: 1,
    style: cytoscape.stylesheet()
        .selector('node')
        .css({
            'height': nodeW,
            'width': nodeH,
            'shape': 'ellipse',
            'border-width': 0,
            'border-style': 'solid',
            'border-color': '#ccc',
            'background-fit': 'cover cover'
        })
        .selector(':selected')
        .css({
            'border-width': 3,
            'border-style': 'double',
            'border-color': '#fc5b32',
            'border-opacity': 0.8
        })
        .selector('.chk')
        .css({
            'border-width': 3,
            'border-style': 'double',
            'border-color': '#fc5b32',
            'border-opacity': 0.8
        })
        .selector('.eating')
        .css({
            'border-color': 'red'
        })
        .selector('.eater')
        .css({
            'border-width': 8
        })
        .selector('edge')
        .css({
            'curve-style': 'bezier',
            'width': 1,
            'line-color': '#aaa',
            "label": "data(label)",
            "font-size": "12px",
            "color": "#666",
            'target-arrow-shape': 'triangle',
            'target-arrow-color': '#aaa'
        })
        .selector('.highlight')
        .css({
            'line-color': '#F00'
        }),
    "elements": {
        "nodes": [],
        "edges": []
    }
});

var options = {
    name: 'cose-bilkent',
    idealEdgeLength: 150,
    concentric: function(node) {
        return node.degree();
    },
    levelWidth: function(nodes) {
        return 1;
    },
    directed: false,
    avoidOverlap: true
}
cy.layout(options).run();


//切换视图
$('.layouts').on('click', function() {
    options.name = $(this).attr('data-layout');
    if (options.name == "concentric") {
        options.minNodeSpacing = 60;
        options.avoidOverlap = true;
        //options.concentric=function(ele){ return ele.data('weight'); }
        options.concentric = function(node) {
            return node.totalDegree();
            //return node.degree();
        }
        options.levelWidth = function(nodes) {
            return 1;
        }
    }
    cy.layout(options).run();
});


//获取关联图数据
function getGraph() {
    $.ajax({
        type: 'get',
        url: unifiedUserUrl10011 + '/case/graph/show/' + pid,
        xhrFields: { withCredentials: true },
        //async:false,
        success: function(result) {
            console.log(result)
            if (result != null && result != '') {
                graph = result.data;
                console.log(graph);
                graph.panningEnabled = true;
                graph.userPanningEnabled = true;
                graph.elements.nodes = JSON.parse(
                    JSON.stringify(graph.elements.nodes).replace(/\"displayname\"\:/g, '"name":').replace(/\"icon\"\:/g, '"image":')
                )
                graph.style = [{
                        "selector": "node",
                        "style": { "height": "30px", "width": "30px", "shape": "ellipse", "border-color": "#ccc", "border-width": "0px", "border-style": "solid", "background-fit": "cover cover" }
                    },
                    {
                        "selector": ":selected",
                        "style": { "border-color": "#fc5b32", "border-opacity": "0.8", "border-width": "3px", "border-style": "double" }
                    },
                    {
                        "selector": ".chk",
                        "style": { "border-color": "#fc5b32", "border-opacity": "0.8", "border-width": "3px", "border-style": "double" }
                    },
                    {
                        "selector": ".eating",
                        "style": { "border-color": "red" }
                    },
                    {
                        "selector": ".eater",
                        "style": { "border-width": "8px" }
                    },
                    {
                        "selector": "edge",
                        "style": {
                            "width": "1px",
                            "line-color": "#aaa",
                            "curve-style": "bezier",
                            'target-arrow-shape': 'triangle',
                            'target-arrow-color': '#aaa'
                        }
                    },
                    {
                        "selector": ".highlight",
                        "style": { "line-color": "#F00" }
                    }
                ];
                graph.zoomingEnabled = true;
                graph.userZoomingEnabled = true;
                graph.panningEnabled = true;
                graph.userPanningEnabled = true;
                cy.json(graph);
                cy.layout(options).run(); //console.log(cy);
            } else {
                $.ajax({
                    type: 'POST',
                    url: unifiedUserUrl + 'relationgraph',
                    data: { 'data': JSON.stringify(cy.json()) },
                    async: true,
                    xhrFields: { withCredentials: true },
                    success: function(data, textStatus) {
                        if (textStatus == 'success') {

                        }
                    }
                });
            }

            //获取cookie
            var newNodes = unescape(getCookie('objdetailData'));
            creatNewNodes(newNodes);

            //初始化节点、连线
            cy.nodes(function(n) {
                var node = n.data();
                n.style({ 'background-image': node['image'], 'content': node['name'] });
                n.unselect();
            });
        }
    });
}
getGraph();


//获取cookie数据创建新节点(因为不能持久化即在不同tab页，添加时不能即时反馈到另一个关联页面上，暂时搁置)
function creatNewNodes(newNodes) {
    if (newNodes != null && newNodes != 'null') {
        newNodes = JSON.parse(newNodes);
        //var tempArr = [];
        var postData = {
            "pid": parent.pid,
            "nodes": [],
            "edges": []
        };
        for (var i = 0; i < newNodes.length; i++) {
            var icon = '';
            //获取实体名称、头像
            $.ajax({
                type: 'get',
                url: unifiedUserUrl + 'object/' + newNodes[i]["objectUri"],
                async: false,
                xhrFields: { withCredentials: true },
                success: function(data) {
                    icon = data.icon;
                }
            });
            // var tempx = getRandom(nodeW, cy.width() - nodeW),
            // 	tempy = getRandom(nodeH, cy.height() - nodeH);
            // var graphinfo = {
            // 	"classes": "",
            // 	"style": { "background-image": icon, "content": newNodes[i]["displayName"] },
            // 	"grabbable": true,
            // 	"group": "nodes",
            // 	"locked": false,
            // 	"position": {"x": tempx, "y": tempy},
            // 	"removed": false,
            // 	"selectable": true,
            // 	"selected": false
            // }
            //后台传值的点的格式	
            postData.nodes.push({
                "id": "",
                "displayname": newNodes[i]["displayName"],
                "icon": icon,
                "objecttype": newNodes[i]["type"],
                "objecturi": newNodes[i]["objectUri"],
                "rowkey": newNodes[i]["rowKey"],
                "owneridcard": owneridcard
                    //"graphinfo":JSON.stringify(graphinfo)
            });
        }
        $.ajax({
                url: unifiedUserUrl10011 + '/case/graph/save',
                type: "post",
                xhrFields: { withCredentials: true },
                contentType: "application/json ",
                data: JSON.stringify(postData),
                success: function(response) {
                    if (response.status == 200) {
                        cy.add(JSON.parse(
                            JSON.stringify(response.data.nodes).replace(/\"displayname\"\:/g, '"name":').replace(/\"icon\"\:/g, '"image":')
                        ))
                        setCookie('objdetailData', null)
                    }
                },
                error: function() {
                    layer.msg('保存数据异常!');
                }
            })
            // $.ajax({
            // 	type: 'POST',
            // 	url: unifiedUserUrl + 'relationgraph',
            // 	data: { 'data': JSON.stringify(cy.json()) },
            // 	async: true,
            // 	xhrFields: { withCredentials: true },
            // 	success: function (data, textStatus) {
            // 		if (textStatus == 'success') {
            // 		}
            // 	}
            // });
    }
}

//初始化节点、连线
cy.nodes(function(n) {
    var node = n.data();
    n.style({ 'background-image': node['image'], 'content': node['name'] });
    n.unselect();
    //n.position({'x':n.position().x,'y':n.position().y});
});


//右键点击事件
cy.on('cxttapstart', 'node', function(evt) {
    posx = cy.$(this).renderedPosition('x');
    posy = cy.$(this).renderedPosition('y');
    cxturi = cy.$(this).data()['objecturi'];
    cxtrowkey = cy.$(this).data()["rowkey"];
    nodeId = cy.$(this).data()["id"];
    //$('input[name=primaryId]').val(cy.$(this).data()['objecturi']),
    //$('input[name=primaryRowkey]').val(cxtid);
});

cy.on('cxttapstart', function(evt) {
    if (evt.target === cy) {
        $('.ctxmenu').html('');
    } else {
        if (evt.target.isNode()) {
            $('.ctxmenu').html('');
            init();
        } else if (evt.target.isEdge()) {
            //console.log(cy.$(this));
            //cy.$(this).remove();
        } else {
            $('.ctxmenu').html('');
        }
    }
});

//鼠标移上节点
var timer;
cy.on('mouseover', 'node', function() {
    var uritemp = cy.$(this).data().objecturi,
        rowkeytemp = cy.$(this).data().rowkey,
        tempx = cy.$(this).renderedPosition('x'),
        tempy = cy.$(this).renderedPosition('y');;
    timer = setTimeout(function() { essentialInfo(uritemp, rowkeytemp, tempx, tempy) }, 2000);
});
cy.on('mouseout', 'node', function() {
    clearTimeout(timer);
    $('.essentialInfo').remove();
});

function essentialInfo(uritemp, rowkeytemp, tempx, tempy) {

    $.ajax({
        type: 'get',
        //url:unifiedUserUrl+'object/'+uri,
        url: unifiedUserUrl + 'object/' + uritemp + '/instance/' + rowkeytemp + '/property',
        async: false,
        xhrFields: { withCredentials: true },
        success: function(data) {
            var strHtml = '';
            strHtml += '<div class="essentialInfo" style="position:absolute; left:' + tempx + 'px; top:' + tempy + 'px;"><ul>';
            for (var i = 0; i < data.length; i++) {
                if (data[i].uri != instanceIcon) {
                    var address = '';

                    if (data[i].type == "GisData") {
                        strHtml += '<li>' + data[i].displayName + '：' + data[i].values[0].value.location + '</li>';
                    } else {
                        strHtml += '<li>' + data[i].displayName + '：' + (data[i].values.length !== 0 ? data[i].values[0].value : "") + '</li>';
                    }
                }
            }
            strHtml += '</ul></div>';
            $('#relationBox').append(strHtml);
        }
    })
}

//左键单击节点
var tempid = 0;
cy.on('tap', 'node', function() {
    if (isChecked()) {
        var chknum = 0;
        chknum = cy.$('node:selected').length;
        //cy.autounselectify(false);
        if (chknum == 0) {

            $('input[name=primaryId]').val(cy.$(this).data()['objecturi']);
            $('input[name=primaryRowkey]').val(cy.$(this).id());
            //cy.$(this).select().addClass('selected');
        } else if (chknum == 1) {
            //cy.autounselectify(true);
            console.log(cy.$(this).data())
            $('input[name=secondaryId]').val(cy.$(this).data()['objecturi']);
            $('input[name=secondaryRowkey]').val(cy.$(this).id());

            //console.log($('input[name=primaryRowkey]').val()+':'+$('input[name=secondaryRowkey]').val());
            tempid = (new Date()).getTime();
            /*cy.add({
            	"data": {
            		"source": $('input[name=primaryRowkey]').val(),
            		"target": $('input[name=secondaryRowkey]').val(),
            		"tempid": tempid,
            		//"timeInterval":data["timeInterval"]
            	},
            	"position": {},
            	"group": "edges",
            	"removed": false,
            	"selected": false,
            	"selectable": true,
            	"locked": false,
            	"grabbable": true,
            	"classes": ""
            });*/
            createRelation();
        }
        cy.$(this).select().addClass('selected');
        //$('input[name=secondaryId]').val(cy.$(this).data()['objecturi']);
        //$('input[name=secondaryRowkey]').val(cy.$(this).id());
        //createRelation();
    } else if (isbeeline()) {
        cy.autounselectify(true);
        $('input[name=secondaryId]').val(cy.$(this).data()['objecturi']);
        $('input[name=secondaryRowkey]').val(cy.$(this).id());
        shortestPath();
    } else {
        cy.autounselectify(false);
        cy.$('node').removeClass('chk');
        cy.$(this).select().addClass('selected');

        var uri = cy.$(this).data()['objecturi'],
            rowkey = cy.$(this).data()["rowkey"],
            title = cy.$(this).data()['name'];
        //console.log(uri+','+rowkey+','+title);
        $('#objShow').html(getExample(uri, rowkey, title));
        $('.scrollbar').mCustomScrollbar();

        $('a.iconfile img').attr('src', $('input[name=iconImg]').val());
        //console.log(cy.$id(rowkey).style['background-image']);

        var temptxt = '',
            etxt = '';
        $('span.editable').on('focus', function() {
            temptxt = $(this).text();
            //console.log(etxt);
        });

        //更换图标
        var icoHtml = '';
        /*icoHtml+='<div><p><input type="file" name="iconfile" value="" /></p><p><input type="button" name="iconsubbtn" value="提交" /></p>';
        icoHtml+='<p><img id="avatarPreview" src="img/fileY.jpg" title="点击更换图片" style="position: absolute; z-index: 9; float: left; width: 100px; height: 100px"></p>';
        icoHtml+='</div>';*/

        icoHtml += '<div class="Frm-upImgBox imgIcoSm M-12 Mt-12">';
        icoHtml += '<input name="iconfile" type="file" style="position: absolute;float: left;margin-left:120px;margin-top: 65px; z-index: 10;width: 200px; height: 25px;" />';
        icoHtml += '<img id="avatarPreview" src="img/fileY.jpg" title="点击更换图片" style="position: absolute; z-index: 9; float: left; width: 100px; height: 100px">';
        icoHtml += '</div>';
        icoHtml += '<div class="D-TcFoot">';
        icoHtml += '<button name="iconsubbtn" class="btn btnF btnWd back2 JQ-addEnt">确定</button>';
        icoHtml += '<button class="btn JQ-qut">取消</button>';
        icoHtml += '</div>';



        $('a.iconfile').on('click', function() {
            layer.open({
                type: 1,
                title: '修改图标',
                area: ['350px', '210px'], //宽高
                content: icoHtml,
                success: function(layero, index) {
                    $("input[name=iconfile]").on('change', function() {
                        var obj = $("input[name=iconfile")[0].files[0];
                        var fr = new FileReader();
                        fr.onload = function() {
                            $("#avatarPreview").attr('src', this.result);
                            //console.log(this.result);
                            //$(layero).find("#avatar").val(this.result);
                        };
                        fr.readAsDataURL(obj);
                        fileUpload($("input[name=iconfile]")[0].files[0]);
                        //console.log(obj)
                    })


                    var fileUpload = function(obj) {
                        var file = obj;
                        //判断类型是不是图片
                        if (!/image\/\w+/.test(file.type)) {
                            alert("请确保文件为图像类型");
                            return false;
                        }

                        var reader = new FileReader();
                        reader.readAsDataURL(file);
                        reader.onload = function(e) {
                            var img = new Image,
                                width = 120, //图片resize宽度
                                quality = 1.0, //图像质量
                                canvas = document.createElement("canvas"),
                                drawer = canvas.getContext("2d");
                            img.src = this.result;
                            canvas.width = width;
                            canvas.height = width * (img.height / img.width);
                            drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
                            img.src = canvas.toDataURL();
                            $("#imgSrc").val(img.src)
                            var image_base64 = img.src.replace("data:image/png;base64,", "");

                        }
                    }

                    $('button[name=iconsubbtn]').on('click', function() {
                        $.ajax({
                            type: 'post',
                            url: unifiedUserUrl + 'object/uploadObjectIco  ',
                            data: { 'rowkey': rowkey, 'objectUri': uri, 'icon': $("#imgSrc").val() },
                            xhrFields: { withCredentials: true },
                            success: function(data, textStatus) {
                                if (textStatus == 'success') {
                                    layer.msg('修改成功！', {
                                        time: 2000
                                    }, function() {
                                        cy.$('#' + rowkey).style({ 'background-image': $("#imgSrc").val() });
                                        cy.$('#' + rowkey).data()['image'] = $("#imgSrc").val();
                                        $('a.iconfile img').attr('src', $("#imgSrc").val());
                                        saveauto = true;
                                        $('.saveGraph').trigger('click');
                                        layer.closeAll();
                                    });
                                }
                            }
                        });
                    });

                    $('.JQ-qut').on('click', function() {
                        layer.close(index);
                    });

                }
            });
        });

        //添加相关对象、相关事件
        createEntity(uri, rowkey);
        docMediaFun(uri, rowkey);

        //新增属性
        $('.addproperty').on('click', function() {
            $('#propertyBox').find('#islink').text('com.scistor.property.');
            $('#propertyBox').find('#conceal').show();
            var strCont = $('#propertyBox').html();
            layer.open({
                type: 1,
                title: '新增属性',
                area: ['500px', '380px'],
                btn: ['确定', '取消'],
                content: strCont,
                yes: function(index, layero) {
                    var displayName = $(layero).find('input[name=txtName]').val(),
                        pyuri = $(layero).find('input[name=txtUri]').val(),
                        options = $(layero).find('select[name=selType] option:selected').val(),
                        description = $(layero).find('textarea[name=txtDescription]').val();

                    //var groupName = group[0].name
                    if (displayName == "") {
                        layer.msg('显示名称不可以空', { icon: 5 });
                        return
                    }
                    if (pyuri == "") {
                        layer.msg('URI不可以为空', { icon: 5 });
                        return
                    }

                    console.log({ 'displayName': displayName, 'uri': pyuri, 'type': options, 'description': description });

                    $.ajax({
                        type: 'POST',
                        url: unifiedUserUrl + 'property' + '?bindTo=' + uri,
                        data: { 'displayName': displayName, 'uri': pyuri, 'type': options, 'description': description },
                        xhrFields: { withCredentials: true },
                        success: function(data, textStatus) {
                            if (textStatus == 'success') {
                                layer.msg('添加成功！', {
                                    time: 2000
                                }, function() {
                                    //displayName
                                    var strHtml = '';
                                    strHtml += '<tr><td class="TxR FsH9">' + data.displayName + '：</td><td class="FsH0"><span class="editable" data-uri="' + data.uri + '" contenteditable="true"></span></td></tr>';
                                    $('#relatedProperty').append(strHtml);
                                    editProperty('post', true);
                                    layer.closeAll();
                                });
                            }
                        }
                    });

                }
            })
        });


        //编辑属性
        editProperty('put', true);

        function editProperty(sptype, isexist) {
            $('.editable').on('blur', function() {

                var duri = $(this).attr('data-uri'),
                    $obj = $(this);
                if (isexist) {
                    var objuri = uri,
                        rk = rowkey,
                        etxt = $obj.text();
                } else {
                    var objuri = $obj.attr('data-objecturi'),
                        rk = $obj.attr('data-rowkey'),
                        etxt = $obj.val(),
                        iscreate = $obj.attr('data-iscreate');
                    if (iscreate) {
                        sptype = 'post';
                    } else {
                        sptype = 'put';
                    }
                }
                console.log(duri);
                if (temptxt != etxt) {
                    $.ajax({
                        type: sptype,
                        url: unifiedUserUrl + 'object/' + objuri + '/instance/' + rk + '/property' + '?uri=' + duri + '&value=' + etxt,
                        //data:{'uri':duri,'value':etxt},
                        xhrFields: { withCredentials: true },
                        success: function(data, textStatus) {
                            //console.log(data);
                            if (textStatus == 'success') {
                                console.log(data);
                                $obj.attr('data-iscreate', false);
                                layer.msg('修改成功！', {
                                    time: 2000
                                })
                            }
                        }
                    })
                }
                temptxt = '';
                etxt = '';
            });
        }

        //转换对象
        var relationNodeArr = []; //相关联节点集合
        $('.conversion').on('click', function() {
            console.log(JSON.stringify(relationNodeArr));
            if (uri == entityqq) {
                $.ajax({
                    type: 'post',
                    url: unifiedUserUrl + 'drug/doChangeQQWechatToDrug',
                    data: { 'qqnum': $('input[name=qqipt]').val(), 'wechatnum': '', 'rowkey': rowkey, 'relationList': JSON.stringify(relationNodeArr) },
                    xhrFields: { withCredentials: true },
                    success: function(data) {
                        console.log(JSON.stringify(data));
                        /*cy.$('#'+rowkey).data({'id':data[0].rowkey,'image':data[0].icon,'rowkey':data[0].rowkey,'uri':data[0].objectUri});
                        cy.$('#'+rowkey).style({'background-image':data[0].icon});
                        $('a.iconfile img').attr('src',data[0].icon);*/

                        var strHtml = '';
                        strHtml += '<div class="editproperties"><div class="tabs clearfix"><ul>'
                        var tempArr = [peoplename, cartid, phonenumber, weixinid, qqnum]
                        for (var i = 0; i < data.length; i++) {
                            var propertyList = data[i]['propertyList'];
                            var lalArr = [];
                            for (var j = 0; j < tempArr.length; j++) {
                                for (var k = 0; k < propertyList.length; k++) {
                                    if (tempArr[j] == propertyList[k]['propertyUri'] && propertyList[k]['value'] != '') {
                                        lalArr.push({ 'rk': data[i]['rowkey'], 'icon': data[i]['icon'], 'uri': data[i]['objectUri'], 'vl': propertyList[k]["value"] });
                                    }
                                }
                            }
                            strHtml += '<li data-rowkey="' + lalArr[0]["rk"] + '" data-icon="' + lalArr[0]["icon"] + '" data-uri="' + lalArr[0]["uri"] + '" data-displayName="' + lalArr[0]["vl"] + '"><input type="checkbox" class="chkcobj" name="chkcobj" value="' + i + '" /><span>' + lalArr[0]["vl"] + '</span></li>';
                        }
                        strHtml += '</ul></div>';
                        strHtml += '<div class="properties clearfix">';
                        for (var i = 0; i < data.length; i++) {
                            if (i > 0) {
                                strHtml += '<div class="list" style="display:none;">';
                            } else {
                                strHtml += '<div class="list">';
                            }
                            var propertyList = data[i]['propertyList'];
                            for (var j = 0; j < propertyList.length; j++) {
                                strHtml += '<dl><dt>' + propertyList[j]["displayName"] + '：</dt>';
                                if (propertyList[j]["value"] != '') {
                                    strHtml += '<dd><input class="editable" data-uri="' + propertyList[j]["propertyUri"] + '" data-rowkey="' + data[i]["rowkey"] + '" data-objecturi="' + data[i]["objectUri"] + '" data-iscreate="' + propertyList[j]["isCreate"] + '" type="text" name="" value="' + propertyList[j]["value"] + '" /></dd></dl>';
                                } else {
                                    strHtml += '<dd><input class="editable" data-uri="' + propertyList[j]["propertyUri"] + '" data-rowkey="' + data[i]["rowkey"] + '" data-objecturi="' + data[i]["objectUri"] + '" data-iscreate="' + propertyList[j]["isCreate"] + '" type="text" name="" value="' + propertyList[j]["value"] + '" /></dd></dl>';
                                }
                            }
                            strHtml += '</div>';

                        }
                        strHtml += '</div>';
                        strHtml += '</div>';

                        //编辑新对象属性
                        layer.open({
                            type: 1,
                            title: '编辑属性',
                            btn: ['确定'],
                            closeBtn: 0,
                            area: ['515px', '380px'],
                            content: strHtml,
                            yes: function(index, layero) {
                                var tempNodeArr = [];
                                if ($('input[name=chkcobj]:checked').size() > 0) {
                                    $.each($('input[name=chkcobj]:checked'), function() {
                                        var iptvl = $(this).val();
                                        var $parent = $(this).parent();
                                        var tempx = getRandom(nodeW, cy.width() - nodeW),
                                            tempy = getRandom(nodeH, cy.height() - nodeH);
                                        cy.add({
                                            "data": {
                                                "id": $parent.attr('data-rowkey'),
                                                "name": $parent.attr('data-displayName'),
                                                "image": $parent.attr('data-icon'),
                                                "uri": $parent.attr('data-uri'),
                                                "rowkey": $parent.attr('data-rowkey')
                                            },
                                            "position": {
                                                "x": tempx,
                                                "y": tempy
                                            },
                                            "style": { 'background-image': $parent.attr('data-icon'), 'content': $parent.attr('data-displayName') },
                                            "group": "nodes",
                                            "removed": false,
                                            "selected": false,
                                            "selectable": true,
                                            "locked": false,
                                            "grabbable": true,
                                            "classes": ""
                                        });
                                        var edgeList = data[iptvl]["edgeList"];
                                        for (var j = 0; j < edgeList.length; j++) {

                                            var linkName = '';
                                            $.ajax({
                                                type: 'get',
                                                url: unifiedUserUrl + 'link/' + edgeList[j]["linkeType"] + '  ',
                                                async: false,
                                                xhrFields: { withCredentials: true },
                                                success: function(res) {
                                                    linkName = res.displayName;
                                                }
                                            });

                                            cy.add({
                                                "data": {
                                                    "linkid": edgeList[j]["linkeId"],
                                                    "source": edgeList[j]["rowkey"],
                                                    "target": edgeList[j]["targetRowkey"],
                                                    "label": linkName,
                                                    "linkuri": edgeList[j]["linkeType"]
                                                },
                                                "position": {},
                                                "group": "edges",
                                                "removed": false,
                                                "selected": false,
                                                "selectable": true,
                                                "locked": false,
                                                "grabbable": true,
                                                "classes": ""
                                            });
                                        }
                                    });
                                    cy.$('#' + rowkey).remove();
                                    $('#objShow').html('');
                                    layer.closeAll();
                                } else {
                                    layer.msg('请至少选择一个对象！', {
                                        time: 2000
                                    });
                                }
                            }
                        })
                        editProperty('put', false);
                        $.each($('.editproperties .tabs li span'), function(i) {
                            $(this).on('click', function() {
                                $('.editproperties .properties').find('.list:eq(' + i + ')').show().siblings().hide();
                            });
                        })
                    }
                });
            }
        });

        //相关节点连线高亮显示
        cy.edges(function(n) {
            var edge = n.data();
            n.classes('');
            if (edge.source == rowkey || edge.target == rowkey) {
                n.classes('highlight');
                cy.$('#' + edge.target).addClass('chk');
                cy.$('#' + edge.source).addClass('chk');
                //console.log(edge);
                //drugObjectUri
                //drugRowkey
                //linkType
                console.log(edge.linkuri);
                if (edge.source == rowkey) {
                    console.log(JSON.stringify(cy.$('#' + edge.target).data()));
                    relationNodeArr.push({ 'drugObjectUri': cy.$('#' + edge.target).data()['linkuri'], 'drugRowkey': cy.$('#' + edge.target).data()['rowkey'], 'linkType': edge.linkuri });
                } else {
                    console.log(JSON.stringify(cy.$('#' + edge.source).data()));
                    relationNodeArr.push({ 'drugObjectUri': cy.$('#' + edge.source).data()['linkuri'], 'drugRowkey': cy.$('#' + edge.source).data()['rowkey'], 'linkType': edge.linkuri });
                }
                //relationNodeArr.push({'drugObjectUri':cy.$('#'+rowkey).data()['objectUri'],'drugRowkey':cy.$('#'+rowkey).data()['rowkey']});
                cy.nodes(function() {

                });
            }

        });
        //cy.layout(options).run();
    }

});
cy.on('tapstart', function() {
    var t = setTimeout(function() { $('.ctxmenu').html('') }, 200);
});

//左键单击边事件
cy.on('tap', 'edge', function() {
    console.log(cy.$(this));
    var linkid = cy.$(this).data()['id'],
        linklabel = cy.$(this).data()['label']
    temptxt = '',
        etxt = '';
    $('#objShow').html(edgesProperty(linkid));

    //新增属性
    $('.addproperty').on('click', function() {
        $('#propertyBox').find('#islink').text('com.scistor.link.property.');
        $('#propertyBox').find('#conceal').hide();
        var strCont = $('#propertyBox').html();
        layer.open({
            type: 1,
            title: '新增属性',
            area: ['500px', '380px'],
            btn: ['确定', '取消'],
            content: strCont,
            yes: function(index, layero) {
                var displayName = $(layero).find('input[name=txtName]').val(),
                    pyuri = $(layero).find('input[name=txtUri]').val(),
                    options = 'String'; //$(layero).find('select[name=selType] option:selected').val(),
                description = $(layero).find('textarea[name=txtDescription]').val();

                if (displayName == "") {
                    layer.msg('显示名称不可以空', { icon: 5 });
                    return
                }
                if (pyuri == "") {
                    layer.msg('URI不可以为空', { icon: 5 });
                    return
                }

                console.log();

                $.ajax({
                    type: 'POST',
                    url: unifiedUserUrl + 'object/createLinkPro',
                    data: { 'linkId': linkid, 'linkProUri': pyuri, 'linkProDisplay': displayName, 'mc': description },
                    xhrFields: { withCredentials: true },
                    success: function(data, textStatus) {
                        if (textStatus == 'success') {
                            layer.msg('添加成功！', {
                                time: 2000
                            }, function() {
                                var strHtml = '';
                                strHtml += '<tr><td class="TxR FsH9">' + displayName + '：</td><td class="FsH0"><span class="editable" data-uri="' + pyuri + '" contenteditable="true"></span></td></tr>';
                                $('#linkProperty').append(strHtml);
                                editProperty('POST');
                                layer.closeAll();
                            });
                        }
                    }
                });

            }
        })
    });

    $('span.editable').on('focus', function() {
        temptxt = $(this).text();
    });

    //编辑属性
    editProperty('POST');

    function editProperty(sptype) {
        $('span.editable').on('blur', function() {
            etxt = $(this).text();
            var duri = $(this).attr('data-uri');
            console.log(duri);
            if (temptxt != etxt) {
                $.ajax({
                    type: sptype,
                    url: unifiedUserUrl + 'object/createLinkPro',
                    data: { 'linkId': linkid, 'linkProUri': duri, 'value': etxt },
                    xhrFields: { withCredentials: true },
                    success: function(data, textStatus) {
                        console.log(data);
                        if (textStatus == 'success') {
                            console.log(data);
                            layer.msg('编辑成功！', {
                                time: 2000
                            })
                        }
                    }
                })
            }
            temptxt = '';
            etxt = '';
        });
    }

});

//鼠标移上边
var linetimer;
cy.on('mouseover', 'edge', function() {
    console.log(cy.$(this).data()['linklabel']);

    cy.$(this).data().label = cy.$(this).data()['linklabel'];
    //cy.layout(options).run();
    /*//console.log(234);
    var uritemp = cy.$(this).data().uri,
    	rowkeytemp = cy.$(this).data().rowkey,
    	tempx=cy.$(this).renderedPosition('x'),
    	tempy=cy.$(this).renderedPosition('y');;
    timer=setTimeout(function(){essentialInfo(uritemp,rowkeytemp,tempx,tempy)},2000);*/
});
cy.on('mouseout', 'edge', function() {
    clearTimeout(linetimer);
    cy.$(this).data().label = '';
    //$('.essentialInfo').remove();
});


//是否选中创建关系
function isChecked() {
    var chked = false;
    if ($('.relationship').hasClass('ischked')) {
        chked = true;
    } else {
        chked = false;
    }
    return chked;
}
$('.relationship').on('click', function() {

    //cy.$('node').unselect().removeClass('selected');
    cy.$('node').removeClass('chk');
    cy.$('edge').removeClass('highlight');
    cy.$('node').unselect().removeClass('selected');

    if (!$(this).hasClass('ischked')) {
        $(this).addClass('ischked');
    } else {
        $(this).removeClass('ischked');
    }

    /*var chknum = 0;
    chknum = cy.$('node:selected').length;
	
    if(chknum>0){
    	if(!$(this).hasClass('ischked')){
    		$(this).addClass('ischked');
    		$('input[name=primaryId]').val(cy.$('node:selected').data()['objecturi']);
    		$('input[name=primaryRowkey]').val(cy.$('node:selected').id());
    	}else{
    		$(this).removeClass('ischked');
    		$('input[name=primaryId]').val('');
    		$('input[name=primaryRowkey]').val('');
    	}
    }else{
    	layer.msg('请选择一个节点', {
    	  	time: 2000
    	}); 
    }*/
});

//创建关系
function createRelation() {

    var primaryId = $('input[name=primaryId]').val(),
        primaryRowkey = $('input[name=primaryRowkey]').val(),
        secondaryId = $('input[name=secondaryId]').val(),
        secondaryRowkey = $('input[name=secondaryRowkey]').val();
    if (primaryRowkey == secondaryRowkey) {
        layer.alert("请勿选择同一结点创建关系!")
        return
    }
    var suc = false;

    var strCont = '';
    $.ajax({
        type: "get",
        url: unifiedUserUrl + 'object/' + primaryId + '/link',
        xhrFields: { withCredentials: true },
        success: function(data) {
            var isCreate = false,
                vindex = 0,
                relationtxt = '';

            strCont += '<div class="relationBox"><ul>';
            strCont += '<li><label>选择关系：</label>';
            strCont += '<select class="seltype"><option value="0">现有关系</option><option value="1">新建关系</option></select></li>';
            strCont += '<li vl="0" class="selli"><label>&nbsp;</label><select id="selRelation">';
            for (var i = 0; i < data.length; i++) {
                strCont += '<option data-linkuri="' + data[i]["uri"] + '">' + data[i]['displayName'] + '</option>';
            }
            strCont += '</select></li>';
            strCont += '<li vl="1" class="selli" style="display:none;"><label>&nbsp;</label><input type="text" name="newrelation" class="txt" style="width:186px;" value="" /></li>';
            strCont += '<li><label>&nbsp;</label><input type="button" class="btn relationBtn" value="创建关系" /></li>';
            strCont += '</ul></div>';

            layer.open({
                type: 1,
                title: '创建关系',
                area: ['340px', '200px'], //宽高
                content: strCont,
                cancel: function(index, layero) {
                    $('input[name=secondaryId]').val('');
                    $('input[name=secondaryRowkey]').val('');
                }
            });

            $('.seltype').on('change', function() {
                vindex = $(this).val();
                $('.relationBox li.selli').hide();
                $('.relationBox li[vl=' + vindex + ']').show();
            });

            $('.relationBtn').one('click', function() {
                var linkuri = '';
                if (vindex == 0) {
                    linkuri = $('#selRelation option:selected').attr('data-linkuri');
                    relationtxt = $('#selRelation option:selected').text();
                } else {
                    isCreate = true;
                    relationtxt = linkuri = $('input[name=newrelation]').val();
                }
                $.ajax({
                    type: "POST",
                    url: unifiedUserUrl + 'relationgraph/analysis/relation',
                    data: { 'createLink': isCreate, 'activeObjectUri': primaryId, 'activeRowKey': primaryRowkey, 'passiveObjectUri': secondaryId, 'passiveRowKey': secondaryRowkey, 'linkUri': linkuri },
                    async: true,
                    xhrFields: { withCredentials: true },
                    success: function(data, textStatus) {
                        console.log("添加边！")
                        console.log(data);
                        if (textStatus == 'success') {
                            var tips = '成功创建关系';
                            if (data["created"] == false) {
                                tips = '边已存在';
                            }
                            var postData = {
                                "pid": pid,
                                "nodes": [],
                                "edges": []
                            };
                            // var graphinfo = {
                            // 	"position": {},
                            // 	"group": "edges",
                            // 	"removed": false,
                            // 	"selected": false,
                            // 	"selectable": true,
                            // 	"locked": false,
                            // 	"grabbable": true,
                            // 	"classes": ""
                            // }
                            postData.edges.push({
                                    "id": "",
                                    "source": primaryRowkey,
                                    "target": secondaryRowkey,
                                    "displayname": relationtxt,
                                    "rowkey": data.linkId,
                                    "linkuri": data["target"]["linkUri"],
                                    "starttime": data["timeInterval"]["startTime"],
                                    "endtime": data["timeInterval"]["endTime"]
                                        //"graphinfo": JSON.stringify(graphinfo)
                                })
                                //将添加的连线保存到后台
                            $.ajax({
                                url: unifiedUserUrl10011 + '/case/graph/save',
                                type: "post",
                                xhrFields: { withCredentials: true },
                                contentType: "application/json ",
                                data: JSON.stringify(postData),
                                success: function(response) {
                                    if (response.status == 200) {
                                        var edgeData = response.data.edges[0]
                                        cy.add(edgeData);
                                        layer.msg(tips, {
                                            time: 2000
                                        }, function() {
                                            $('.relationship').removeClass('ischked');
                                            $('input[name=primaryId]').val('');
                                            $('input[name=primaryRowkey]').val('');
                                            $('input[name=secondaryId]').val('');
                                            $('input[name=secondaryRowkey]').val('');
                                            layer.closeAll();
                                        });
                                    }
                                }
                            })
                        }
                    }
                });
            });

        }
    });

}

//是否选中最短路径
function isbeeline() {
    var chked = false;
    if ($('.beeline').hasClass('ischked')) {
        chked = true;
    } else {
        chked = false;
    }
    return chked;
}
$('.beeline').on('click', function() {
    var chknum = 0;
    chknum = cy.$('node:selected').length;
    //console.log(chknum);
    if (chknum > 0) {
        if (!$(this).hasClass('ischked')) {
            $(this).addClass('ischked');
            $('input[name=primaryId]').val(cy.$('node:selected').data()['objecturi']);
            $('input[name=primaryRowkey]').val(cy.$('node:selected').id());
        } else {
            $(this).removeClass('ischked');
            $('input[name=primaryId]').val('');
            $('input[name=primaryRowkey]').val('');
        }
    } else {
        layer.msg('请选择一个节点', {
            time: 2000
        });
    }
});

//最短路径
function shortestPath() {

    var primaryId = $('input[name=primaryId]').val(),
        primaryRowkey = $('input[name=primaryRowkey]').val(),
        secondaryId = $('input[name=secondaryId]').val(),
        secondaryRowkey = $('input[name=secondaryRowkey]').val();

    var strCont = '';
    var nodefirst = '{"objectUri":"' + primaryId + '","rowKey":"' + primaryRowkey + '"}';
    var nodesecond = '{"objectUri":"' + secondaryId + '","rowKey":"' + secondaryRowkey + '"}';
    //console.log(nodefirst);console.log(nodesecond);
    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'object/instance/shortestpath  ',
        data: { "source": nodefirst, "target": nodesecond },
        xhrFields: { withCredentials: true },
        success: function(data) {

            //console.log(data);

            strCont += '<div class="feelineBox"><ul>';
            for (var i = 0; i < data.length; i++) {
                var temprk = '';
                for (var j = 0; j < data[i].length; j++) {
                    temprk += data[i][j]["rowKey"] + ',';
                }
                if (temprk.length > 0) {
                    temprk = temprk.substring(0, temprk.length - 1);
                }
                strCont += '<li><input type="radio" id="line-' + i + '" name="lines" value="' + i + '" /><label class="route" data-route="' + temprk + '" for="line-' + i + '">路径' + (i + 1) + '</label></li>';
            }
            strCont += '</ul></div>';


            layer.open({
                type: 1,
                title: '最短路径',
                area: ['340px', '200px'], //宽高
                content: strCont,
                cancel: function(index, layero) {
                    $('input[name=secondaryId]').val('');
                    $('input[name=secondaryRowkey]').val('');
                    $('.beeline').removeClass('ischked');
                    cy.$('edge:selected').remove();
                }
            });

            $('label.route').on('click', function() {

                cy.$('edge:selected').remove();

                var rk = $(this).attr('data-route').split(",");
                var rowkeyfirst = rk[0],
                    rowkeysecond = rk[1];

                for (var i = 0; i < rk.length; i++) {
                    if (i < rk.length - 1) {
                        cy.add({
                            "data": {
                                "source": rk[i],
                                "target": rk[i + 1]
                            },
                            "position": {},
                            "group": "edges",
                            "removed": false,
                            "selected": true,
                            "selectable": true,
                            "locked": false,
                            "grabbable": true,
                            "classes": "highlight",
                            "custom": true
                        })
                    }
                }

            });

        }
    });
}


//保存关联图
// $('.saveGraph').on('click', function () {
// 	var graph = cy.json();
// 	//console.log('bc:'+JSON.stringify(graph));
// 	$.ajax({
// 		type: 'POST',
// 		url: unifiedUserUrl + 'relationgraph',
// 		data: { 'data': JSON.stringify(graph) },
// 		xhrFields: { withCredentials: true },
// 		success: function (data, textStatus) {
// 			if (!saveauto) {
// 				if (textStatus == 'success') {
// 					layer.msg('成功保存关联图', {
// 						time: 2000
// 					}, function () {
// 					});
// 				}
// 			} else {
// 				console.log(555);
// 				saveauto = false;
// 			}
// 		}
// 	});
// });


//获取快照
getSnapshot();

function getSnapshot() {
    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'relationgraph/' + pid + '/snapshot',
        //async:true,
        xhrFields: { withCredentials: true },
        success: function(data) {
            var snapHtml = '';
            for (var i = 0; i < data.length; i++) {
                snapHtml += '<dl data-id="' + data[i]["id"] + '"><a class="del" title="删除" href="javascript:"></a><p class="img"><img class="imgAuto" src="' + data[i]["snapshot"] + '" alt="" /></p><h6>' + formatDate(data[i]["timeCreated"]) + '</h6></dl>';
            }
            $('#historyImg').html(snapHtml);

            //根据快照ID获取快照数据
            $('#historyImg dl').on('click', function() {
                var snapid = $(this).attr('data-id');
                $.ajax({
                    type: 'get',
                    url: unifiedUserUrl + 'relationgraph/snapshot/' + snapid,
                    xhrFields: { withCredentials: true },
                    success: function(result) {
                        graph = JSON.parse(result.data);
                        console.log(graph)
                        cy.json(JSON.parse(result.data));
                        cy.layout(options).run();
                        createDemos();
                    }
                });
            });

            //根据快照ID删除快照
            $('#historyImg dl a.del').on('click', function(e) {
                e.stopPropagation();
                var snapid = $(this).parent('dl').attr('data-id');
                var that = $(this);
                $.ajax({
                    type: 'DELETE',
                    url: unifiedUserUrl + 'relationgraph/snapshot/' + snapid,
                    xhrFields: { withCredentials: true },
                    success: function(data, textStatus) {
                        if (textStatus == 'success') {
                            layer.msg('成功删除快照', {
                                time: 2000
                            }, function() {
                                that.parents('dl').remove();
                            });
                        }
                    }
                });
            });

        }
    });
}


//生成快照
$('.snapshot').on('click', function() {

    var graph = cy.json(),
        snap = cy.png({ full: true });
    //生成的快照中设置ping yi
    graph.panningEnabled = true;
    graph.userPanningEnabled = true;
    // graph.caseId = pid;
    // alert(JSON.stringify(graph));
    $.ajax({
        type: 'post',
        url: unifiedUserUrl + 'relationgraph/snapshot',
        data: { 'snapshot': snap, 'caseId': pid, 'data': JSON.stringify(graph) },
        xhrFields: { withCredentials: true },
        success: function(data, textStatus) {
            getSnapshot();
            $('.snapshot').addClass('isFd');
            if (textStatus == 'success') {
                layer.msg('成功创建快照', {
                    time: 2000
                }, function() {

                });
            }

        }
    });

});


//实例关联操作
function relationFun(primaryId, primaryRowkey, tp) {

    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'object/' + primaryId + '/instance/' + primaryRowkey + '/' + tp,
        xhrFields: { withCredentials: true },
        success: function(data) {
            //console.log(data);

            if (data != null && data.length > 0) {
                var uriArr = [],
                    rnewArr = [],
                    strHtml = '';
                for (var i = 0; i < data.length; i++) {
                    var obj = { 'uri': data[i].objectInfo.uri, 'displayName': data[i].objectInfo.displayName };
                    obj = JSON.stringify(obj);
                    uriArr.push(obj);
                }
                rnewArr = uriArr.distinct();

                strHtml += '<div id="choose">';
                for (var i = 0; i < rnewArr.length; i++) {
                    var rtemp = JSON.parse(rnewArr[i]);
                    strHtml += '<p><label class="ipt-choose"><input type="checkbox" name="choose" value="' + rtemp.uri + '" />' + rtemp.displayName + '</label></p>';
                }
                strHtml += '</div>'

                var isFirst = true;
                layer.open({
                    title: '选择关联条件',
                    content: strHtml,
                    btn: ['确定', '取消'],
                    yes: function() {
                        var showArr = [];
                        if (isFirst) {
                            $.each($('input[name=choose]:checked'), function() {
                                var vl = $(this).val();
                                for (var i = 0; i < data.length; i++) {
                                    if (data[i].objectUri == vl) {
                                        showArr.push(data[i]);
                                    }
                                }
                            });
                            isFirst = false;
                            relationHandle(showArr, nodeId);
                        }
                        layer.closeAll();
                    },
                    cancel: function() {
                        layer.closeAll();
                    }
                });

            }

        }
    });
}

function relationHandle(data, nodeId) {
    //console.log('实例关联：'+data);
    var tempx1 = posx < 175 ? 25 : (posx - 150),
        tempx2 = posx > 955 ? 955 : (posx + 150),
        tempy1 = posy < 175 ? 25 : (posy - 150),
        tempy2 = posy > 955 ? 925 : (posy);

    var nodeArr = [],
        lineArr = [];
    //var nodesArr = graph['elements']['nodes'];
    //界面已有点
    var nodesArr = cy.json()['elements']['nodes'];
    //var tempedges = [];
    for (var j = 0; j < nodesArr.length; j++) {
        for (var i = 0; i < data.length; i++) {
            if (data[i]["rowKey"] == nodesArr[j]["data"]["rowkey"]) {
                //tempedges.push(data[i]);
                data.splice(i, 1);
                i--;
            }
        }
    }
    //console.log(data);
    //console.log(tempedges);
    var postData = {
        "pid": pid,
        "root": nodeId,
        "edges": []
    }
    for (var i = 0; i < data.length; i++) {
        // var tempx = getRandom(tempx1, tempx2),
        // 	tempy = getRandom(tempy1, tempy2);
        // var graphinfo = {
        // 	"classes": "",
        // 	"style": { "background-image": data[i]["objectInfo"]["icon"], "content": data[i]["displayName"] },
        // 	"grabbable": true,
        // 	"group": "nodes",
        // 	"locked": false,
        // 	"position": { "x": tempx, "y": tempy },
        // 	"removed": false,
        // 	"selectable": true,
        // 	"selected": false
        // };
        // var graphinfo_link = {
        // 	"position": {},
        // 	"group": "edges",
        // 	"removed": false,
        // 	"selected": false,
        // 	"selectable": true,
        // 	"locked": false,
        // 	"grabbable": true,
        // 	"classes": ""
        // }
        postData.edges.push({
                "id": "",
                "linkuri": data[i]["linkUri"],
                "rowkey": data[i]["linkId"],
                "source": cxtrowkey,
                "displayname": data[i]["linkDisplayName"],
                "target": data[i]["rowKey"],
                //"graphinfo": JSON.stringify(graphinfo_link),
                "starttime": "",
                "endtime": "",
                "node": {
                    "id": "",
                    "rowkey": data[i]["rowKey"],
                    "objecturi": data[i]["objectUri"],
                    "objecttype": data[i]['objectType'],
                    "displayname": data[i]["displayName"],
                    "icon": data[i]["objectInfo"]["icon"]
                        //"graphinfo": JSON.stringify(graphinfo)
                }
            }

        )
    }

    $.ajax({
        url: unifiedUserUrl10011 + '/case/graph/associatenode/save',
        type: "post",
        xhrFields: { withCredentials: true },
        contentType: "application/json ",
        data: JSON.stringify(postData),
        success: function(response) {
            if (response.status == 200) {
                cy.add(JSON.parse(
                    JSON.stringify(response.data.nodes).replace(/\"displayname\"\:/g, '"name":').replace(/\"icon\"\:/g, '"image":')
                ))
                cy.add(JSON.parse(
                        JSON.stringify(response.data.edges).replace(/\"displayname\"\:/g, '"name":')
                    ))
                    //cy.add(newedges);
                cy.nodes(function(n) {
                    var node = n.data();
                    n.unselect();
                    //n.position({'x':n.position().x,'y':n.position().y});
                });

                graph = cy.json();
            }
        }
    })

}


//删除关联事件、关联实体、关联文件、关联多媒体
function relationDel(primaryId, primaryRowkey, tp) {

    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'object/' + primaryId + '/instance/' + primaryRowkey + '/' + tp,
        xhrFields: { withCredentials: true },
        success: function(data) {

            for (var i = 0; i < data.length; i++) {
                var j = cy.$('#' + data[i]["rowKey"]);
                cy.remove(j);
            }

        }
    });

}


//时间轴
var date = $("#date"),
    dateSilderObj; //渲染日期组件

function createDemos() {
    var Months = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"];
    if (graph != null && graph != '') {
        var linkarr = graph['elements']['edges'],
            minarr = [],
            maxarr = [],
            minT = 0,
            maxT = 0;
        cy.nodes(function(n) {
            var node = n.data();
            n.style({ 'background-image': node['image'], 'content': node['name'] });
            n.unselect();
        });
        graph = cy.json()
        if (linkarr != null && linkarr.length > 0) {
            for (var i = 0; i < linkarr.length; i++) {
                minarr.push(linkarr[i].data.starttime);
                maxarr.push(linkarr[i].data.endtime);
            }

            minT = Math.min.apply(null, minarr);
            maxT = Math.max.apply(null, maxarr);

            dateSilderObj = date.dateRangeSlider({
                arrows: true, //是否显示左右箭头
                bounds: { min: new Date(minT), max: new Date(maxT) }, //最大 最少日期
                defaultValues: { min: new Date(minT), max: new Date(maxT) } //默认选中区域
                ,
                scales: [{
                    first: function(value) { return value; },
                    end: function(value) { return value; },
                    next: function(val) {
                        var next = new Date(val);
                        return new Date(next.setMonth(next.getMonth() + 1));
                    },
                    label: function(val) {
                        return Months[val.getMonth()];
                    },
                    format: function(tickContainer, tickStart, tickEnd) {
                        tickContainer.addClass("myCustomClass");
                    }
                }]
            }); //日期控件

            //重新赋值（整个时间轴）
            dateSilderObj.dateRangeSlider("bounds", new Date(minT), new Date(maxT));

            //重新赋值（选中区域）
            dateSilderObj.dateRangeSlider("values", new Date(minT), new Date(minT));

            //拖动完毕后的事件
            dateSilderObj.bind("valuesChanged", function(e, data) {

                cy.$('edge:selected').remove();

                var val = data.values;
                var stime = formatDate(val.min);
                var etime = formatDate(val.max);

                for (var i = 0; i < linkarr.length; i++) {
                    if (linkarr[i].data.starttime >= val.min && linkarr[i].data.endtime <= val.max) {
                        cy.add({
                            "data": {
                                "source": linkarr[i].data.source,
                                "target": linkarr[i].data.target
                            },
                            "position": {},
                            "group": "edges",
                            "removed": false,
                            "selected": true,
                            "selectable": true,
                            "locked": false,
                            "grabbable": true,
                            "classes": "highlight",
                            "custom": true
                        })
                    } else {
                        //linkarr[i]["color"]='#eee';
                    }
                }
            });

            //$('#dateSlider #date').remove();

        }
        //快照中没有线的情况
        else {
            cy.nodes(function(n) {
                var node = n.data();
                n.style({ 'background-image': node['image'], 'content': node['name'] });
                n.unselect();
            });
            graph = cy.json()
        }
    }
}

createDemos();

//清空关联图
$('.cleargraph').on('click', function() {
    if (cy.$(':selected').length > 0) {
        cy.$(':selected').remove();
    } else {
        cy.$('node').remove();
    }
});

//操作关联图
//上
$('.handlebox span.up').on('click', function() {
    //cy.panningEnabled(true);

    cy.animate({
        pan: { y: cy.pan('y') + 25 }
    }, {
        duration: 200
    });

});
//下
$('.handlebox span.down').on('click', function() {
    //cy.panningEnabled(true);
    cy.animate({
        pan: { y: cy.pan('y') - 25 }
    }, {
        duration: 200
    });
});
//左
$('.handlebox span.left').on('click', function() {
    //cy.panningEnabled(true);
    cy.animate({
        pan: { x: cy.pan('x') + 25 }
    }, {
        duration: 200
    });
});
//右
$('.handlebox span.right').on('click', function() {
    //cy.panningEnabled(true);
    cy.animate({
        pan: { x: cy.pan('x') - 25 }
    }, {
        duration: 200
    });
});
//是否可移动
$('.handlebox span.hand').on('click', function() {
    $(this).toggleClass('selected');
    if ($(this).hasClass('selected')) {
        cy.panningEnabled(true);
        cy.userPanningEnabled(true);
    } else {
        cy.panningEnabled(false);
        cy.userPanningEnabled(false);
    }
});
//缩小
$('.handlebox span.narrow').on('click', function() {
    cy.animate({
        zoom: cy.zoom() * 9 / 10
    }, {
        duration: 200
    });
});
//放大
$('.handlebox span.enlarge').on('click', function() {
    cy.animate({
        zoom: cy.zoom() * 10 / 9
    }, {
        duration: 200
    });
});
//初始大小
$('.handlebox span.adapt').on('click', function() {
    cy.animate({
        zoom: 1
    }, {
        duration: 200
    });
});

//框选
$('.boxselection').on('click', function() {
    $(this).toggleClass('ischked');
    if ($(this).hasClass('ischked')) {
        cy.panningEnabled(false);
        cy.userPanningEnabled(false);
    } else {
        cy.panningEnabled(true);
        cy.userPanningEnabled(true);
    }
});

//关键路径
$('.prvotal2').on('click', function() {

    var strCont = '';
    strCont += '<div class="relationBox"><ul>';
    strCont += '<li><label>手机号：</label><input type="text" class="txt prvotalval" value="" /></li>';
    strCont += '<li><label>&nbsp;</label><input type="button" class="btn prvotalBtn" value="关键路径" /></li>';
    strCont += '</ul></div>';

    var prvotal = layer.open({
        type: 1,
        title: '关键路径',
        area: ['340px', '200px'], //宽高
        content: strCont,

    });

    $('.prvotalBtn').on('click', function() {
        var val = $('.prvotalval').val();
        prvotalFun(val, unifiedUserUrl + '/graph/searchMiddleman/' + val);
        layer.close(prvotal);
        layer.msg('图表生成中...')
    });

});
$('.prvotal').on('click', function() {


    prvotalFun(0, unifiedUserUrl + '/graph/searchMiddleman');


    /*$.ajax({
    	type:'get',
    	url:unifiedUserUrl+'/graph/getMaxTotal  ' ,
    	success:function(data){
    		console.log(data);
    		var strHtml='';
    		for(var i=0;i<data.length;i++){
    			for (var item in data[i]) {
    				strHtml+='<tr>';
    				strHtml+='<td class="TxR FsH9">'+item+'：</td><td><span class="census">'+data[i][item]+'</span></td>';
    				strHtml+='</tr>';
    			}
    		}
    		/*for (var item in data) {
    			strHtml+='<tr>';
    			strHtml+='<td class="TxR FsH9">'+item[0]+'：</td><td><span class="census">'+data[item][1]+'</span></td>';
    			strHtml+='</tr>';
    		}*/
    /*$('#Statistics').html(strHtml);
}
})*/
});

//var times=2;
function prvotalFun(val, linkurl) {

    //cy.zoom(0.1);
    //cy.remove(cy.elements('node'));
    //$('#relationBox').width(cy.width()*3).height(cy.height()*2).css({'overflow':'hidden'});

    $.ajax({
        type: 'get',
        url: linkurl,
        //timeout:30000,
        xhrFields: { withCredentials: true },
        success: function(datas) {
            console.log(datas);
            var eles;
            if (datas != null) {
                var tempArr = [],
                    linkArr = [];

                var ndid;

                var total = datas.total,
                    data = datas.result;
                console.log(total);
                console.log(data);
                var strHtml = '';
                for (var i = 0; i < total.length; i++) {
                    strHtml += '<tr>';
                    strHtml += '<td class="TxR FsH9"><a class="orientate" data-rowkey="' + total[i][0]["rowkey"] + '" href="javascript:">' + total[i][0]["displayName"] + '</a>：</td><td><span class="census"><a class="orientate" data-rowkey="' + total[i][0]["rowkey"] + '" href="javascript:">' + total[i][0]["count"] + '</a></span></td>';
                    strHtml += '</tr>';
                }
                $('#Statistics').html(strHtml);

                //点击选中节点
                $('a.orientate').on('click', function() {
                    var rk = $(this).attr('data-rowkey');
                    //cy.autounselectify(false);
                    //cy.$('node').unselect().removeClass('selected');
                    cy.$('node').removeClass('chk');
                    //cy.$('#'+rk).addClass('selected');

                    //相关节点连线高亮显示
                    cy.edges(function(n) {
                        var edge = n.data();
                        n.classes('');
                        //cy.$('node').removeClass('selected');
                        if (edge.source == rk || edge.target == rk) {
                            n.classes('highlight');
                            cy.$('#' + edge.target).addClass('chk');
                        }
                    });

                });

                if (data != null && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        for (var j = 0; j < data[i].length; j++) {
                            ndid = data[i][0]['rowKey'];
                            var tempx = getRandom(nodeW, cy.width() - nodeW),
                                tempy = getRandom(nodeH, cy.height() - nodeH);
                            tempArr.push({
                                "data": {
                                    "id": data[i][j]["rowKey"],
                                    "name": data[i][j]["displayName"],
                                    "image": data[i][j]["icon"],
                                    //"label": data[i][j]["displayName"],
                                    "uri": data[i][j]["objectUri"],
                                    "rowkey": data[i][j]["rowKey"],
                                    "linkuri": data[i][0]["linkUri"]
                                },
                                "position": {
                                    "x": tempx,
                                    "y": tempy
                                },
                                "style": { 'content': data[i][j]['displayName'], 'background-image': data[i][j]['icon'] },
                                "group": "nodes",
                                "removed": false,
                                "selected": false,
                                "selectable": true,
                                "locked": false,
                                "grabbable": true,
                                "classes": ""
                            })

                        }

                        if (data[i].length > 1) {
                            if (data[i][0]["rowKey"] != data[i][1]["rowKey"]) {
                                linkArr.push({
                                    "data": {
                                        "linkid": data[i][0]["linkId"],
                                        "source": data[i][0]["rowKey"],
                                        "target": data[i][1]["rowKey"],
                                        "linklabel": data[i][0]['linkDisplayName'],
                                        "linkuri": data[i][0]["linkUri"]
                                    },
                                    "position": {},
                                    "group": "edges",
                                    "removed": false,
                                    "selected": true,
                                    "selectable": true,
                                    "locked": false,
                                    "grabbable": true,
                                    "custom": true
                                })
                            }
                        }

                    }

                    eles = cy.add(tempArr);
                    cy.add(linkArr);


                    graph = cy.json();
                    layer.closeAll();
                }
            }

            options = {
                name: 'cose-bilkent',
                nodeDimensionsIncludeLabels: true,
                idealEdgeLength: 150,
                concentric: function(node) {
                    return node.degree();
                },
                levelWidth: function(nodes) {
                    return 1;
                },
                tile: false,
                padding: 100,
                randomize: true,
                directed: false,
                avoidOverlap: true
            }
            cy.layout(options).run();
            /*eles.betweennessCentrality({
            	/*options.concentric=function(node){
            		return node.totalDegree();
            		//return node.degree();
            	}*/
            /*weight:function(edge){
            	return edge.totalDegree();
            },
            directed:true*/
            //});*/

            /*if(times>0){
            	setTimeout('prvotalFun(0,"'+unifiedUserUrl+'graph/searchGang  ' +'")',2000);
            	times--;
            }*/
        }
    })

}

//缩略图
cy.navigator({
    container: $('.cytoscape-navigator')
});
//放大缩小
cy.panzoom({
    fitSelector: $('.cy-panzoom')
});

$('.locking').on('click', function() {
    prvotalFun(0, unifiedUserUrl + 'graph/searchGang');
});

$('.extend').on('click', function() {
    prvotalFun(0, unifiedUserUrl + 'graph/searchConnectGraph');
});

$('.gang').on('click', function() {
    prvotalFun(0, unifiedUserUrl + 'graph/searchThGraph');
});

//添加对象
$('.ch_ene').on('click', function() {
    layer.open({
        type: 2,
        closeBtn: true,
        area: ['640px', '552px'],
        shift: 7,
        title: '+添加',
        shadeClose: true,
        content: 'obj-add.html?isgraph=true',
        success: function(layero, index) {

        }
    });
});

function addObjFun(obj) {
    obj.style = { 'background-image': obj.data.icon, 'content': obj.data.displayname };
    cy.add(JSON.parse(
        JSON.stringify(obj).replace(/\"displayname\"\:/g, '"name":').replace(/\"icon\"\:/g, '"image":')
    ))
}

//添加相关对象、相关事件
var relateType = '',
    poptype = '';;

function createEntity(objectUri, instanceUri) {
    console.log('ddd:' + instanceUri);
    $('.addEntity').on('click', function() {
        relateType = $(this).attr('data-type'), otype = '+添加';
        if (relateType.localeCompare("Entity") == 0) {
            otype = "+添加实体";
        }
        if (relateType.localeCompare("Event") == 0) {
            otype = "+添加事件";
        }
        layer.open({
            type: 2,
            closeBtn: true,
            area: ['640px', '552px'],
            shift: 7,
            title: otype,
            shadeClose: true,
            //content: $("#addqxpz").html(),
            content: 'obj-model.html' + '?objectUri=' + objectUri + '&type=' + relateType + '&instanceUri=' + instanceUri + '&isgraph=true',
            success: function(layero, index) {}
        });
    });
}

function correlationFun(data, instanceUri) {
    var tempx = getRandom(nodeW, cy.width() - nodeW),
        tempy = getRandom(nodeH, cy.height() - nodeH);
    var obj = data.target;
    console.log(JSON.stringify(obj));
    cy.add({
        "data": {
            "id": obj.rowKey,
            "name": obj.displayName,
            "label": obj.displayName,
            "image": obj.objectInfo.icon,
            "uri": obj.objectUri,
            "rowkey": obj.rowKey
        },
        "position": {
            "x": tempx,
            "y": tempy
        },
        "style": { 'background-image': obj.objectInfo.icon, 'content': obj.displayName },
        "group": "nodes",
        "removed": false,
        "selected": false,
        "selectable": true,
        "locked": false,
        "grabbable": true,
        "classes": ""
    });
    cy.add({
        "data": {
            "source": instanceUri,
            "target": obj.rowKey,
            "timeInterval": obj.objectInfo.timeCreated,
            "linklabel": obj.linkDisplayName
        },
        "position": {},
        "group": "edges",
        "removed": false,
        "selected": false,
        "selectable": true,
        "locked": false,
        "grabbable": true,
        "classes": ""
    });

    var slink = '';
    if (relateType == 'Entity' || relateType == 'Event') {
        slink = 'obj-show-obj.html';
    } else {
        if (poptype == 'Doc') {
            slink = 'obj-show-doc.html';
        } else if (poptype == 'Media') {
            slink = 'obj-show-media.html';
        }
    }
    var url = encodeURI(encodeURI(slink + "?instanceUri=" + obj.rowKey + "&objectUri=" + obj.objectUri + "&displayName=" + encodeURI(obj.displayName))),
        iHtml = '<em><a target="_blank" href="' + url + '"><img src="' + obj.objectInfo.icon + '" alt="" width="30px;"/></a></em>';
    var strHtml = '<li>' + iHtml + '<a target="_blank"style="line-height:30px;" title="' + obj.objectInfo.displayName + '" href="' + url + '">' + obj.displayName + '-' + obj.objectInfo.displayName + '</a></li>';
    if (relateType.localeCompare("Entity") == 0) {
        $('#relatedEntity').prepend(strHtml);
    }
    if (relateType.localeCompare("Event") == 0) {
        $('#relatedEvent').prepend(strHtml);
    }
    if (poptype.localeCompare("Doc") == 0) {
        $('#relatedDoc').prepend(strHtml);
    }
    if (poptype.localeCompare("Media") == 0) {
        $('#relatedMedia').prepend(strHtml);
    }
}

//上传文档、多媒体
function docMediaFun(objectUri, instanceUri) {
    $('.docMedia').on('click', function() {
        poptype = $(this).attr('data-type');
        if (poptype.localeCompare("Doc") == 0) {
            otype = "+上传文档";
        }
        if (poptype.localeCompare("Media") == 0) {
            otype = "+上传多媒体";
        }
        layer.open({
            type: 2,
            closeBtn: true,
            area: ['640px', '520px'],
            shift: 7,
            title: otype,
            shadeClose: true,
            //content: $("#addqxpz").html(),
            content: 'related-popup.html' + '?objectUri=' + objectUri + '&poptype=' + poptype + '&instanceUri=' + instanceUri,
            success: function(layero, index) {}
        });
    });
}

$(".exportData").click(function() {
    $.ajax({
        url: unifiedUserUrl + "relationgraph/export/pxml",
        type: 'post',
        data: { "taskid": "1" },
        xhrFields: { withCredentials: true },
        success: function(data) {
            console.log(data)
        },
        error: function() {
            console.log("导出失败！");
        }
    })
})

//添加协作人
$(document).on("click", ".addHelper", function() {
        layer.open({
            type: 2,
            closeBtn: true,
            area: ['1140px', '620px'],
            shift: 7,
            title: '+添加协作人',
            shadeClose: true,
            content: 'relation_addHelper.html',
            success: function(layero, index) {

            }
        });
    })
    //共享功能
$(document).on("click", ".share", function() {
        $.ajax({
            url: unifiedUserUrl10011 + '/case/graph/share/' + pid,
            type: "post",
            xhrFields: { withCredentials: true },
            success: function(data) {
                console.log(data)
                if (data.status == 200) {
                    layer.alert("操作成功！")
                    websock.send(JSON.stringify(cy.json()))
                }
            },
        })
    })
    //删除节点
$(document).on("click", ".deleteNodes", function() {
        var nodesLength = cy.$('node:selected').length;
        var nodesArr = cy.$('node:selected');
        if (nodesLength === 0) {
            layer.alert("请选择要删除的节点！")
            return
        }
        var postData = [];
        for (var i = 0; i < nodesLength; i++) {
            postData.push(nodesArr[i].id())
            if (nodesArr[i].data()["owneridcard"].indexOf(owneridcard) === -1) {
                layer.alert(nodesArr[i].data()['name'] + "点非本角色创建，无法删除！");
                return false;
            }
        }
        $.ajax({
            url: unifiedUserUrl10011 + "/case/graph/delete/" + pid,
            type: "post",
            data: { "nodes": postData.toString() },
            xhrFields: { withCredentials: true },
            success: function(data) {
                if (data.status == 200) {
                    layer.alert("删除成功！")
                    cy.$('node:selected').remove();
                    websock.send(JSON.stringify(cy.json()))
                }
            }
        })

    })
    //导出案件数据
$(document).on("click", ".exportCaseData", function() {
    var selectedNodes = cy.$('node:selected');
    var selectedNodesArr = [];
    if (selectedNodes.length === 0) {
        selectedNodes = cy.json().elements.nodes
        for (var i = 0; i < selectedNodes.length; i++) {
            selectedNodesArr.push(selectedNodes[i].data.id)
        }
    } else {
        for (var i = 0; i < selectedNodes.length; i++) {
            selectedNodesArr.push(selectedNodes[i].id())
        }
    }
    console.log(selectedNodes)
    layer.open({
        type: 2,
        closeBtn: true,
        area: ['640px', '600px'],
        shift: 7,
        title: '导出案件数据',
        shadeClose: true,
        content: 'relation_exportCaseData.html',
        success: function(layero, index) {
            checkedNodes = selectedNodesArr
        }
    });
})